import { useState, useEffect } from 'react';

const receiveDataSource = (res, property, view, pageAxis, setOptions, getOptions) => {
  let list = [];
  if (pageAxis.isSuccessProps(res)) {
    if (res.action && res.data) res = res.data;
    if (property.listName) list = res[property.listName];
    else list = res;
  }
  property.dataSource = list;
  if (property.setDataSourceFn) {
    const fn = pageAxis.getFunction(property.setDataSourceFn);
    if (fn) fn(property);
  }
  if (!property.isOnlyInit) setOptions(getOptions(property, view, pageAxis));
};

const setServiceDataSource = (property) => {
  const { valueName, textName, serviceInterface, isRefresh } = property;
  property.serviceDataSource = {
    valueName,
    textName,
    stateName: serviceInterface.actionName,
    serviceName: serviceInterface.serviceName,
    actionName: serviceInterface.actionName,
    isCache: !isRefresh,
  };
};

export default (property, view, pageAxis, getOptions, refreshId) => {
  const [options, setOptions] = useState([]);

  useEffect(() => {
    if (property.data && property.data[property.name + "_DataSource"]) {
      property.dataSource = property.data[property.name + "_DataSource"];
    }

    if (!property.serviceDataSource && property.serviceInterface) setServiceDataSource(property);

    const { dataSource, serviceDataSource } = property;
    let isCache = !(serviceDataSource && serviceDataSource.isCache === false);
    if (property.isCache === false) isCache = false;
    if (dataSource && isCache) {
      setOptions(getOptions(property, view, pageAxis));
      return;
    }

    if (serviceDataSource) {
      const state = pageAxis.getStateValue(serviceDataSource.stateName);
      if (isCache && pageAxis.isSuccessProps(state) && !serviceDataSource.isRefresh) receiveDataSource(state, property, view, pageAxis, setOptions, getOptions);
      else {
        let payload = serviceDataSource.payload || {};
        const getPayload = serviceDataSource.getPayload || property.getPayload;
        if (getPayload) {
          payload = pageAxis.getFunction(getPayload)({ property, view });
          if (payload === false) return;
        }
        pageAxis.dispatchAction(serviceDataSource.serviceName, serviceDataSource.actionName, payload).then(res => receiveDataSource(res, property, view, pageAxis, setOptions, getOptions));
      }
    }
  }, [property, pageAxis, view, setOptions, getOptions, refreshId]);

  return [options, setOptions];
};
